const multer = require("koa-multer")

const fs = require('fs')

const FilePath = "public/uploads"

const ServerUrl = require("../models/config").ServerUrl

function unlink(file) {
    return new Promise((resolve, reject) => {
       
            fs.unlink(`public/uploads/${file}`,(err) => {
              if (err) {
                reject(err)
              } else {
                resolve("1")
              }
            });
        
    })
}

// 读取图片
function ReadAllImage() {
  let newArr = []
    return new Promise((resolve, reject) => {
      fs.readdir(FilePath, (err, data) => {
        if (err) {
          reject(err)
        } else {
          data.forEach( el => {
            newArr.push(`${ServerUrl}/${FilePath}/${el}`)
          })
          resolve(newArr)
        }
      })
    })
}

// 写入图片

function writeImage( origin_buffer ) {
  let name= `${new Date().getTime()}.jpg`
   
        return new Promise( (resolve, reject ) => {
          //var base64Img = origin_buffer.toString('base64'); // base64图片编码字符串
         // var dataBuffer = new Buffer(base64Img, 'base64');
          //  fs.writeFile(`public/images/${name}`, dataBuffer, (err,data) => {
          //    if (err) {
          //      reject(err)
          //    } else {
          //      resolve("1")
          //    }
          //  })
          try {
            origin_buffer.pipe(fs.createWriteStream(`public/images/${name}`))
            resolve("1")
          } catch (error) {
            reject(error)
          }
        })
    

}

var storage = multer.diskStorage({
    // 文件保存路径
    destination: function (req, file, cb) {
        cb(null, "public/uploads/")
    },
    filename: function (req, file, cb) {
        var filemat = file.originalname.split(".")
        cb(null, Date.now() + "." + filemat[filemat.length - 1])
    }
})

var upload = multer({ storage })

module.exports = {
    upload,
    unlink,
    ReadAllImage,
    writeImage
}